package com.ftw.commons.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Build
import android.os.Build.VERSION.SDK_INT
import android.provider.Settings
import android.util.DisplayMetrics
import android.view.Display
import java.lang.reflect.Method


/**
 * 描    述：
 * 作    者：fantianwen
 * 时    间：2020-02-03
 */
object OsUtils {
    @SuppressLint("ObsoleteSdkInt")
    fun getScreenHeight(activity: Activity?): Int {
        if (activity == null) {
            return 0
        }
        val display: Display = activity.windowManager.defaultDisplay
        var realHeight = 0
        if (SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            val metrics = DisplayMetrics()
            display.getRealMetrics(metrics)
            realHeight = metrics.heightPixels
        } else {
            try {
                val mGetRawH: Method = Display::class.java.getMethod("getRawHeight")
                realHeight = mGetRawH.invoke(display) as Int
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return realHeight
    }


    @SuppressLint("ObsoleteSdkInt")
    fun getScreenWidth(activity: Activity?): Int {
        if (activity == null) {
            return 0
        }
        val display: Display = activity.windowManager.defaultDisplay
        var realWidth = 0
        if (SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            val metrics = DisplayMetrics()
            display.getRealMetrics(metrics)
            realWidth = metrics.widthPixels
        } else {
            try {
                val mGetRawW: Method = Display::class.java.getMethod("getRawWidth")
                realWidth = mGetRawW.invoke(display) as Int
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return realWidth
    }


    /**
     * 状态栏高度
     */
    fun getStatusBarHeight(activity: Activity): Int {
        val resourceId: Int =
            activity.resources.getIdentifier("status_bar_height", "dimen", "android")
        return activity.resources.getDimensionPixelSize(resourceId)
    }


    /**
     * 获取虚拟键高度(无论是否隐藏)
     *
     * @param context
     * @return
     */
    fun getNavigationBarHeight(context: Context): Int {
        var result = 0
        val resources: Resources = context.resources
        val resourceId: Int = resources.getIdentifier(
            if (isPortrait(context)) "navigation_bar_height" else "navigation_bar_height_landscape",
            "dimen",
            "android"
        )
        if (resourceId > 0) {
            result = context.resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

    /**
     * 手机具有底部导航栏时，底部导航栏是否可见
     * @param activity
     * @return
     */
    @SuppressLint("ObsoleteSdkInt")
    private fun isNavigationBarVisible(activity: Activity): Boolean {
        //判断手机底部是否支持导航栏显示
        val haveNavigationBar =
            checkDeviceHasNavigationBar(
                activity
            )
        if (haveNavigationBar) {
            if (SDK_INT >= 17) {
                val brand = Build.BRAND
                val mDeviceInfo: String
                mDeviceInfo = when {
                    brand.equals("HUAWEI", ignoreCase = true) -> {
                        "navigationbar_is_min"
                    }
                    brand.equals("XIAOMI", ignoreCase = true) -> {
                        "force_fsg_nav_bar"
                    }
                    brand.equals("VIVO", ignoreCase = true) -> {
                        "navigation_gesture_on"
                    }
                    brand.equals("OPPO", ignoreCase = true) -> {
                        "navigation_gesture_on"
                    }
                    else -> {
                        "navigationbar_is_min"
                    }
                }
                if (Settings.Global.getInt(activity.contentResolver, mDeviceInfo, 0) == 0) {
                    return true
                }
            }
        }
        return false
    }

    /**
     * 检测是否具有底部导航栏
     *
     * @param activity
     * @return
     */
    @SuppressLint("PrivateApi")
    private fun checkDeviceHasNavigationBar(activity: Activity): Boolean {
        var hasNavigationBar = false
        val rs: Resources = activity.resources
        val id = rs.getIdentifier("config_showNavigationBar", "bool", "android")
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id)
        }
        try {
            val systemPropertiesClass =
                Class.forName("android.os.SystemProperties")
            val m =
                systemPropertiesClass.getMethod("get", String::class.java)
            val navBarOverride =
                m.invoke(systemPropertiesClass, "qemu.hw.mainkeys") as String
            if ("1" == navBarOverride) {
                hasNavigationBar = false
            } else if ("0" == navBarOverride) {
                hasNavigationBar = true
            }
        } catch (e: java.lang.Exception) {
        }
        return hasNavigationBar
    }

    /**
     * 获取当前底部导航栏高度(隐藏后高度为0)
     *
     * @param activity
     * @return
     */
    fun getCurrentNavigationBarHeight(activity: Activity): Int {
        var navigationBarHeight = 0
        val resources: Resources = activity.resources
        val resourceId: Int = resources.getIdentifier(
            if (isPortrait(activity)) "navigation_bar_height" else "navigation_bar_height_landscape",
            "dimen",
            "android"
        )
        if (resourceId > 0 && checkDeviceHasNavigationBar(
                activity
            ) && !isNavigationBarVisible(
                activity
            )
        ) {
            navigationBarHeight = resources.getDimensionPixelSize(resourceId)
        }
        return navigationBarHeight
    }

    /**
     * 是否为竖屏
     *
     * @param context
     * @return
     */
    private fun isPortrait(context: Context): Boolean {
        return context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
    }

    /**
     * 获取可用屏幕高度，排除虚拟键
     *
     * @param context 上下文
     * @return 返回高度
     */
    fun getContentHeight(context: Activity): Int {
        return getScreenHeight(context) - getCurrentNavigationBarHeight(
            context
        )
    }

}